<?php

namespace App\Http\Controllers\Web;

use App\Http\pay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

class PayController extends Controller {

    public function recharge(Request $request) {
        $returnurl = $_SERVER['HTTP_HOST'] . "/cert";
        $param['returnUrl'] = $returnurl;
        $param['amount'] = '';
        $info = pay::dodealrecharge($param);
        //dd($info);
        header("Location:$info");
        exit();
    }

    public function order_pay(Request $request) {
        $id = $request->input('id');
        $order = DB::table("orders")->where(['sn' => $id, 'order_status' => 1])->first();
        if ($order) {
            //查询用余额
            $param['uid'] = Auth::user()->sysid;
            $userinfo = Pay::getdealaccount($param);
            if ($userinfo['data']['defaultAccount'] < $order->money) {
                echo "<script> alert('余额不足请充值！');parent.location.href='/cert/order'; </script>";
            } else {
                //余额充足及时扣款
                $param['type'] = 'IMMEDIATE';
                $param['price'] = $order->money;
                $param['outTradeNo'] = $order->sn;
                $param['uid'] = $param['uid'];
                $param['remark'] = $order->order_name;
                $re = Pay::dodealdrtpay($param);
                //dd($re);exit;
                if ($re['ok'] != 1) {
                    $redata['id'] = '1';
                    $redata['ms'] = '支付失败';
                    $a = json_encode($redata);
                    echo "<script> alert('支付失败！);parent.location.href='/cert/order'; </script>";
                } else {
                    //支付成功
                    $pay_number = $re['data']['tradeNo'];
                    $pay_time = time();
                    $arr = array('order_status' => 3, 'pay_number' => $pay_number, 'pay_time' => $pay_time);
                    $relust = DB::table("orders")->where("sn", $id)->update($arr);
                    echo "<script> alert('支付成功！');parent.location.href='/cert/order'; </script>";
                }
            }
        }
    }

    public function index() {
        return view("test.pay");
    }

}
